package com.hys.authserver.auth;

import com.hys.authserver.utils.JwtUtils;
import com.hys.authserver.utils.RedisUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private AuthUserDetailsService userDetailsService;

    @Resource
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        final String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authorization != null && authorization.startsWith("Bearer ")) {
            final String token = authorization.substring(7);
            if(StringUtils.isNotBlank(token) && JwtUtils.validateToken(token)) {

                final String uuid = JwtUtils.id(token);
                final String username = JwtUtils.username(token);
                final String phone= JwtUtils.phone(token);

                if (StringUtils.isBlank(redisUtils.getJwtUuidKey(username)) || !uuid.equals(redisUtils.getJwtUuidKey(username))) {
                    throw new RuntimeException("token过期");
                }

                //续期
                redisUtils.setJwtUuidKey(username, uuid);

                final AuthUserDetails userDetails = userDetailsService.loadUserByUsername(phone);
                SecurityContextHolder.getContext().setAuthentication(AuthUserDetails.toToken(userDetails));
            }
        }
        filterChain.doFilter(request, response);
    }
}
